<?php

namespace app\api\services;

use app\api\model\SystemCity;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use function AlibabaCloud\Client\value;

class SystemCityServices
{
    /**
     * 城市数据
     * @return mixed|string
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function cityList()
    {
        return CacheServices::remember('CITY_LIST', function () {
            $allCity = SystemCity::getCityList([], 'city_id as v,name as n ,parent_id');
            $allCity = (new Collection($allCity))->toArray();
            return sort_city_tier($allCity);
        });
    }

    public static function getSonCityList($pid = 0)
    {
        $list = SystemCity::getCityList(['parent_id' => $pid], 'id,city_id,level,name');
//        $list = $this->dao->getCityList(['parent_id' => $pid], 'id,city_id,level,name');
        $parent_name = $pid ? SystemCity::getValue(['city_id' => $pid], 'name') : '中国';
//        $is_add = $pid == 0 || $this->dao->value(['city_id' => $pid], 'parent_id') == 0 ? 1 : 0;
        $is_add = $pid == 0 || SystemCity::getValue(['city_id' => $pid], 'parent_id') == 0 ? 1 : 0;

        $arr = [];
        if ($list) {
            foreach ($list as $item) {
                $data = [];
                $data['id'] = $item['id'];
                $data['city_id'] = $item['city_id'];
                $data['label'] = $item['name'];
                $data['parent_name'] = $parent_name;
                if ($is_add) {
                    $data['children'] = [];
                    $data['hasChildren'] = [];
                    $data['_loading'] = false;
                }
                $arr [] = $data;
            }
        }
        return $arr;
    }
}